import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/i18n/i18n.dart';
import 'package:qunaimedical/models/qa_user.dart';
import 'package:qunaimedical/utils/sp_util.dart';

/// 状态管理
class Store {
  Store._internal();

  // 全局初始化
  static init(Widget child) {
    return MultiProvider(
      providers: [
        // 国际化
        ChangeNotifierProvider.value(
          value: LocaleStore(SPUtil.getLanguageCode()),
        ),
        // 全局信息
        ChangeNotifierProvider.value(
          value: StoreInfo(SPUtil.getQAUser(), 0),
        ),
      ],
      child: child,
    );
  }
}

/// 语言
class LocaleStore with ChangeNotifier {
  String? _languageCode;

  LocaleStore(this._languageCode);

  String? get languageCode => _languageCode;

  set languageCode(String? languageCode) {
    if (languageCode != null && languageCode != _languageCode) {
      _languageCode = languageCode;
      S.locale = Locale(languageCode);
      SPUtil.setLanguageCode(languageCode);
      notifyListeners();
    }
  }

  void setLanguageCode(String languageCode) {
    _languageCode = languageCode;
    SPUtil.setLanguageCode(languageCode);
  }
}

/// 全局信息
class StoreInfo with ChangeNotifier {
  QAUser? _qaUser;
  int _unreadMsgCount;

  /// 未读消息个数
  int get unreadMsgCount => _unreadMsgCount;

  void updateUnreadMsgCount(int value) {
    _unreadMsgCount = value;
    notifyListeners();
  }

  StoreInfo(this._qaUser, this._unreadMsgCount);

  QAUser? get qaUser => _qaUser;

  void updateQAUser(QAUser value) {
    _qaUser = value;
    SPUtil.setQAUser(value);
    notifyListeners();
  }

  /// 清空全局信息
  void clear() {
    _qaUser = null;
    SPUtil.setQAUser(null);
    _unreadMsgCount = 0;
    notifyListeners();
  }
}
